package com.tzjz.controller;

import com.tzjz.dto.Result;

import com.tzjz.entity.CompanyUser;
import com.tzjz.entity.Permission;
import com.tzjz.entity.UserRoleRelation;
import com.tzjz.service.CompanyUserService;
import com.tzjz.service.UserRoleRelationService;
import com.tzjz.utils.JWTUtils;
import com.tzjz.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author renshuting
 * @date 2024/1/6 18:27
 */
@RefreshScope
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Value("${user.id}")
    private String id;
    @Value("${user.name}")
    private String name;
    @Value("${user.age}")
    private String age;

    @Autowired
    private CompanyUserService companyUserService;
    @Autowired
    private UserRoleRelationService userRoleRelationService;

    @GetMapping("login")
    public Result login(String login, String password) throws Exception {
        CompanyUser login1 = companyUserService.findByLogin(login);
        if (!login1.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            return Result.failMessage("密码不对");
        }
        List<Permission> permissionList = companyUserService.getPermissionList(login);
        List<String> refIds = permissionList.stream().map(Permission::getValue).distinct().collect(Collectors.toList());
        String permission = String.join(",", refIds);

        Map<String, String> userData = new HashMap<>();
        userData.put("id", String.valueOf(login1.getId()));
        userData.put("permission", permission);
        String token = JWTUtils.getToken(userData, 86400);
        RedisUtils.set(login, token, 86400);
        RedisUtils.set(token, userData, 86400);
        return Result.success(token);
    }

    @GetMapping("region")
    public Result region(String login, String password, String email) throws Exception {
        CompanyUser companyUser = new CompanyUser();
        companyUser.setId(UUID.randomUUID().variant());
        companyUser.setLogin(login);
        companyUser.setUsername(login);
        companyUser.setEmail(email);
        companyUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        companyUser.setCreateTime(new Date());
        companyUser.setStatus(1);
        try {
            companyUserService.insertUser(companyUser);
        }catch (Exception e){
            throw new Exception("当前用户已存在！");
        }

        UserRoleRelation userRoleRelation = new UserRoleRelation();
        userRoleRelation.setUserId(companyUser.getId());
        userRoleRelation.setRoleId(1);
        userRoleRelationService.insertUserRole(userRoleRelation);

        List<Permission> permissionList = companyUserService.getPermissionList(login);
        List<String> refIds = permissionList.stream().map(Permission::getValue).distinct().collect(Collectors.toList());
        String permission = String.join(",", refIds);

        Map<String, String> map = new HashMap<>();
        map.put("id", String.valueOf(companyUser.getId()));
        map.put("permission", permission);
        String token = JWTUtils.getToken(map, 86400);
        return Result.success(token);
    }

    @GetMapping("getNacosConfig")
    public Result providerTest() {
        log.info("我是user，已成功获取nacos配置中心的数据：(id:"
                + id + ",name:" + name + ",age:" + age + ")");
        return Result.success("我是user，已成功获取nacos配置中心的数据：(id:"
                + id + ",name:" + name + ",age:" + age + ")");
    }
}
